<?php
/**
 * Created by PhpStorm.
 * User: 小蛮哼哼哼
 * Email: 243194993@qq.com
 * Date: 2021/8/9
 * Time: 14:06
 * motto: 现在的努力是为了小时候吹过的牛逼！
 */

declare(strict_types=1);

namespace app\common\business;


use app\common\lib\Show;
use app\common\model\mysql\GoodsSku as ModelObj;
use app\common\validate\GoodsSku as ValidateObj;
use think\Exception;
use think\facade\Log;

class GoodsSku extends BusBase
{
    protected ?ModelObj $modelObj = null;
    protected ?ValidateObj $validateObj = null;
    //是否验证允许重复
    protected bool $repeat = false;
    //验证数据库重复字段
    protected string $repeat_string = 'title';

    public function __construct()
    {
        $this->modelObj = new ModelObj();
        $this->validateObj = new ValidateObj();
    }

    /**
     * @param array $data
     * @param int $goods_id
     * @return false
     * @throws Exception
     */
    public function saveAll(array $data = [], int $goods_id = 0): bool
    {
        $skus = [];
        foreach ($data as $k => $v) {
            $skus[] = [
                'goods_id' => $goods_id,
                "specs_value_ids" => $k,
                "price" => $v['price'],
                "cost_price" => $v['market_price'],
                "images" => $v['picture'],
                "stock" => $v['stock'],
                "status" => $v['status'],
            ];
        }
        //dump($skus);exit();
        Log::info(Show::json_msg($skus));
        try {
            $result = $this->addAll($skus);
        } catch (\Exception $e) {
            throw new Exception($e->getMessage());
        }
        Log::info(Show::json_msg($result));
        if ($result) {
            $res = (new Goods())->updateById($goods_id, [
                'sku_id' => $result[0]['id'],
                "price" => $result[0]['price'],
                "cost_price" => $result[0]['cost_price']
            ]);
            if ($res) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

}